package com.mzj.solr;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;

import com.mzj.util.PropertiesUtils;

public class MSolrClient {
	
	public static Map<String, String> paramMap = null;
	
	static {
		paramMap = PropertiesUtils.getParamMap();
	}

	public static SolrClient getClient(String indexName) {
		String solrUrl = paramMap.get("solr.url");
		solrUrl += "/"+indexName;

		HttpSolrClient client = new HttpSolrClient.Builder(solrUrl)
			    .withConnectionTimeout(10000)
			    .withSocketTimeout(60000)
			    .build();
		return client;
	}
	
	
	public static SolrClient getCloudClient() {
		String zkHosts = paramMap.get("cloud.solr.zookeeper.host");
		String zkroots = paramMap.get("cloud.solr.zookeeper.zkroot");
		return new CloudSolrClient.Builder().withZkHost(zkHosts).withZkChroot(zkroots).build();
	}
	
	
public static RestHighLevelClient getEsClient() {
		
		String urls = paramMap.get("es.client");
		String[] urlList = urls.split("\\,");
		List<HttpHost> list = new ArrayList<HttpHost>();
		for (String urlPort : urlList) {
			String url = urlPort.split("\\:")[0];
			String port = urlPort.split("\\:")[1];
			list.add(new HttpHost(url, Integer.valueOf(port), "http"));
		}
		HttpHost[] arr = new HttpHost[list.size()];
		arr = list.toArray(arr);
		RestClientBuilder builder = RestClient.builder(arr)
				.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
					@Override
					public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
						requestConfigBuilder.setConnectTimeout(5000);
						requestConfigBuilder.setSocketTimeout(40000);
						requestConfigBuilder.setConnectionRequestTimeout(1000);
						return requestConfigBuilder;
					}

				}).setMaxRetryTimeoutMillis(20 * 60 * 1000);
		return  new RestHighLevelClient(builder );
	}

}
